package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import com.lzx.iteam.net.*;
import com.lzx.iteam.task.UpLoadContactsTask;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.TimeButton;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.baidu.location.b.g.m;
import static com.lzx.iteam.DialerApp.mContext;

/**
 * Created by shijunting on 14-12-29.
 */
public class ForgetActivity extends Activity implements View.OnClickListener {

    private Button mBtnReg;
    private TimeButton mRegTimeBtn;
    private EditText mPhoneNumberEt, mVerifycodeEt, mSetPasswdEt;
    private Dialog mProgressDialog;
    private TextView mBack;

    private String mPasswd;
    private String mPhoneNum;

    private PreferenceUtil mPreferenceUtil;
    private LocalLogin loginer;
    private String mRongToken;
    private boolean isStop; // 是否清空倒计时

    public static final int ERROR_PARSE = 1003;
    private static final int MSG_ACTIVE = 2001;
    private static final int MSG_SEND_VERIFY_CODE = 2000;
    public static final String LAST_NUMBER = "last_number";
    private static final String TAG = "ForgetActivity";
    private AsynHttpClient mAsynClient;

    private static final int MSG_GET_EVENT_LIST = 2007;
    private static final int MSG_GET_CLOUD_GROUP_LIST = 2009;
    private static final int MSG_GET_NAMECARD = 1789;
    private static final int MSG_SET_REGISTRATION_ID = 1000;
    private static final int MSG_RONG_TOKEN = 2010;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what){
                case MSG_SEND_VERIFY_CODE:
                    if (msg.arg1 == 0) {
                        showAlertDialog();
                    }else {
                        isStop = true;
                        mRegTimeBtn.onClearTask();
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(ForgetActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(ForgetActivity.this,(String)msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_ACTIVE:
                    mPreferenceUtil.save(PreferenceUtil.TEAM_SID,LocalLogin.getInstance().mSid);
                    mPreferenceUtil.save(PreferenceUtil.USER_PHONE,mPhoneNum);
                    mPreferenceUtil.save(PreferenceUtil.USER_PASS,mPasswd);
                    handleActiveDone(msg);
                    break;
                case MSG_GET_EVENT_LIST:
                    if (msg.arg1 == 0) {
                    }
                    break;
                case MSG_GET_CLOUD_GROUP_LIST:
                    if (msg.arg1 == 0) {
                    }
                    break;
                case MSG_GET_NAMECARD:
                    if (msg.arg1 == 0) {

                    } else {
                        Toast.makeText(ForgetActivity.this, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;
                case MSG_RONG_TOKEN:
                    if (msg.arg1 == 0){
                        try {
                            JSONObject item = ((JSONObject)msg.obj).getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            mRongToken = item.getString("token");
                            connectRongYun();

                        } catch (JSONException e) {
                            Log.e("JSONException",e.toString());
                        }
                    }else{
                        Toast.makeText(mContext, (String) msg.obj,
                              Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forget_ps_layout);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        loginer = LocalLogin.getInstance();
        init();

        mRegTimeBtn.onCreate(savedInstanceState);
        mRegTimeBtn.setOnClickListener(this);
        mRegTimeBtn.setTextBefore("获取验证码").setTextAfter("秒后重新获取").setLenght(60*1000);

        // TODO 当上一次进来的不是这个操作 验证码可点击
        int flag = getIntent().getIntExtra("is_run",0);
        if (flag != Constants.REG_ACTION){
            mRegTimeBtn.onClearTask();
            Constants.REG_ACTION = flag;

        }
    }

    /**
     * 初始化
     */
    private void init() {

        mBtnReg = (Button) findViewById(R.id.btn_forget);
        mRegTimeBtn = (TimeButton) findViewById(R.id.forget_btn_time);
        mPhoneNumberEt = (EditText) findViewById(R.id.phonenumber);
        mVerifycodeEt = (EditText) findViewById(R.id.verifycode);
        mSetPasswdEt = (EditText) findViewById(R.id.set_passwd);
        mBack = (TextView) findViewById(R.id.container_back);
        mBack.setOnClickListener(this);
        mAsynClient = AsynHttpClient.getInstance(this);
        mPhoneNumberEt.setFocusable(true);
        mPhoneNumberEt.setFocusableInTouchMode(true);
        mPhoneNumberEt.requestFocus();
        mBtnReg.setOnClickListener(this);
    }

    private void initViewDisplay() {
            String number = mPreferenceUtil.getString(LAST_NUMBER,"");
            if (!TextUtils.isEmpty(number))
                mPhoneNumberEt.setText(number);
    }


    @Override
    protected void onResume() {
        super.onResume();
        initViewDisplay();
    }

    /**
     * 获取验证码
     */
    private void sendVerifyCode() {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE,LocalLogin.getInstance().mPhoneNum));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE,"1"));

        SendVerifyCodeMessage mobileActiveMsg = new SendVerifyCodeMessage(
                mHandler.obtainMessage(MSG_SEND_VERIFY_CODE));
        mobileActiveMsg.type = 2;
        mobileActiveMsg.mParams = mList;
        mobileActiveMsg.mApi = AsynHttpClient.API_USER_SEND_CODE_PASSWORD;
        mAsynClient.execUserHttp(mobileActiveMsg);
    }


    /**
     *  忘记密码返回的处理
     * @param msg
     */
    private void handleActiveDone(Message msg) {
        if (msg.arg1 == 0) {
            getEventsList("0", 1);
//            getChatGroupList();
//            getCloudGroupList();
            getRongToken();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(ForgetActivity.this.getCurrentFocus()
                    .getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } else {
            httpReqDlgDismiss();
            mRegTimeBtn.onClearTask();
            if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                Toast.makeText(ForgetActivity.this, R.string.active_failure_no_network,
                        Toast.LENGTH_LONG).show();
            } else{
                Toast.makeText(ForgetActivity.this, (String) msg.obj,
                        Toast.LENGTH_LONG).show();

            }

            AllDialogUtil util = new AllDialogUtil(ForgetActivity.this);
            util.titleMsgBtnStyle("错误", "密码找回失败!", "确定");
            mRegTimeBtn.onClearTask();
            isStop = true;
            util.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                @Override
                public void onConfirmClick(Dialog lDialog) {
                    lDialog.dismiss();
                }

                @Override
                public void onCancelClick(Dialog lDialog) {
                }
            });
        }
    }

    /**
     * 验证码 message  RegMsgStructure
     */
    static class SendVerifyCodeMessage extends CcMsgStructure {

        private Message mmCallback;

        public SendVerifyCodeMessage(Message callback) {
            mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            try {
                if (mmCallback != null) {
                    mmCallback.arg1 = 0;
                    mmCallback.sendToTarget();
                }
            } catch (Exception e) {
                if (mmCallback != null) {
                    mmCallback.arg1 = AsynHttpClient.ERROR_SERVER;
                    mmCallback.sendToTarget();
                }
                return;
            }

        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if(mmCallback != null){
                mmCallback.arg1 = error;
                if(!StringUtil.isEmpty(errorMsg)){
                    mmCallback.obj = errorMsg;
                }else{
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    /**
     * 点击按钮 进行的判断
     * @param checkcode true-注册按钮 false-获取验证码按钮
     * @return
     */
    private boolean localCheck(boolean checkcode) {
        mPhoneNum = mPhoneNumberEt.getText().toString().trim();
        mPasswd = mSetPasswdEt.getText().toString().trim();
        String code = mVerifycodeEt.getText().toString().trim();

        LocalLogin.getInstance().mPhoneNum = mPhoneNum;

        if (TextUtils.isEmpty(mPhoneNum)) {
            Toast.makeText(this, R.string.validate_phone_num, Toast.LENGTH_LONG).show();
            return false;
        }

        if (checkcode) {
            if (TextUtils.isEmpty(code)) {
                Toast.makeText(this, R.string.active_code_empty, Toast.LENGTH_LONG).show();
                return false;
            } else if (code.length() < 4) {
                Toast.makeText(this, R.string.active_code_error, Toast.LENGTH_LONG).show();
                return false;
            }
            if (TextUtils.isEmpty(mPasswd) || mPasswd.length() < 6) {
                Toast.makeText(this, R.string.validate_passwd, Toast.LENGTH_LONG).show();
                return false;
            }

        }

        if (!StringUtil.isMobile(mPhoneNum)) {
            Toast.makeText(this, R.string.validate_china_phone_num, Toast.LENGTH_LONG).show();
            return false;
        }

        return true;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.forget_btn_time:
                if (localCheck(false)){
                    if (Constants.isConnect(ForgetActivity.this)){
                        sendVerifyCode();
                        mRegTimeBtn.startTime();
                        mPreferenceUtil.save(LAST_NUMBER, mPhoneNum);
                    }else{
                        Toast.makeText(ForgetActivity.this,R.string.active_failure_no_network,Toast.LENGTH_SHORT).show();
                    }
                }
                break;

            case R.id.btn_forget:
                if (localCheck(true)) {
                    forgot(mVerifycodeEt.getText().toString());
                }
                break;
            case R.id.container_back:
                finish();
                break;
            case R.id.privacy_agreement_tv:
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "使用条款和隐私政策");
                intent.putExtra("type", -2);
                startActivity(intent);
                break;
        }
    }


    /**
     *  忘记密码
     * @param verifyCode 验证码
     */
    public void forgot(String verifyCode) {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE, LocalLogin.getInstance().mPhoneNum));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_PASS,mPasswd));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE,"1"));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_CODE, verifyCode));

        httpReqDlgShow();
        ForgotMessage forgotMsg = new ForgotMessage(this,
                mHandler.obtainMessage(MSG_ACTIVE));
        forgotMsg.type = 2;
        forgotMsg.mParams = mList;
        forgotMsg.mApi = AsynHttpClient.API_USER_FORGETPASS;
        mAsynClient.execUserHttp(forgotMsg);

    }


    /**
     *    忘记密码请求 message
     */
     class ForgotMessage extends CcMsgStructure {

        private Context mmContext;

        private Message mmCallback;

        private String useId;


        public ForgotMessage(Context context, Message callback) {
            mmCallback = callback;
            mmContext = context;
        }

        @Override
        public void onReceive(JSONObject data) {
            try {

                JSONObject result = data.getJSONObject("data");
                LocalLogin.getInstance().mSid = result.getString(AsynHttpClient.KEY_SID_OLD);
                useId = result.getString(AsynHttpClient.KEY_NEW_USEID);
                mPreferenceUtil.save(PreferenceUtil.CLIENT_USEID, useId);

                String securityKey = result.getString(PreferenceUtil.CLIENT_SECURITY_KRY);
                mPreferenceUtil.save(PreferenceUtil.CLIENT_SECURITY_KRY, securityKey);

                setRegistrationId(JPushInterface.getRegistrationID(mmContext));

                if (!StringUtil.isEmpty(LocalLogin.getInstance().mSid)) {
                    StorageData storageData = new StorageData(LocalLogin.getInstance().mPhoneNum, LocalLogin.getInstance().mSid);
                    storageData.writeIn(mmContext, "key.obj");
                    loginer.login(ForgetActivity.this);
                    mmCallback.arg1 = 0;
                } else {
                    mmCallback.arg1 = ERROR_PARSE;
                }
                if (mmCallback != null)
                    mmCallback.sendToTarget();

            } catch (JSONException e) {
                Log.e(TAG, "MobileActiveMessage: " + e.toString());
                if (mmCallback != null)
                    mmCallback.arg1 = ERROR_PARSE;
                if (mmCallback != null)
                    mmCallback.sendToTarget();
            }

        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if(mmCallback != null){
                mmCallback.arg1 = error;
                if(!StringUtil.isEmpty(errorMsg)){
                    mmCallback.obj = errorMsg;
                }else{
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    private void httpReqDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).styleProgress("请稍后...");
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.show();
    }

    private void httpReqDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }



    private void showAlertDialog() {
        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(this);
        String title = getString(R.string.alert_title);
        String message = getString(R.string.alert_message);
        dialogUtil.titleMsgBtnStyle(title, message, getString(R.string.ok));
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
            }
        });
    }


    @Override
    protected void onDestroy() {
        mRegTimeBtn.onDestroy();
        super.onDestroy();
    }


    /**
     * 获取事件列表
     *
     * @param type 事件类型 0. 全部, 1：公告，2：审批，3：周报，4：普通事件，5：自定义  6:系统事件  7：活动 8：投票 9:签到
     */
    public void getEventsList(String type, int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, type));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        EventDataMessage.GetEventListData eventListData = new EventDataMessage.GetEventListData(mHandler.obtainMessage(MSG_GET_EVENT_LIST), ForgetActivity.this, type,1);
        eventListData.mApi = AsynHttpClient.API_EVENT_LIST_V3;
        eventListData.mParams = nvps;
        AsynHttpClient.getInstance(ForgetActivity.this).execEventHttp(eventListData);
    }


    /**
     * 获取团队列表
     */
    public void getCloudGroupList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetGroupListMsg getGroup = new GetGroupListMsg(ForgetActivity.this,mHandler.obtainMessage(MSG_GET_CLOUD_GROUP_LIST));
        getGroup.mApi = AsynHttpClient.API_GROUP_GETLIST;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(ForgetActivity.this).execCcHttp(getGroup);
    }

    /**
     * 获取名片信息
     */
    private void uploadNameCard() {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));

        NameCardMessage message = new NameCardMessage(mHandler.obtainMessage(MSG_GET_NAMECARD),this);
        message.mApi = AsynHttpClient.API_USER_MYNAMECARD;
        message.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(message);

    }

    /**
     * 绑定极光推送唯一 id
     * @param registrationId
     */
    private void setRegistrationId(String registrationId) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair("registration_id", registrationId));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_SET_REGISTRATION_ID));
        message.mApi = AsynHttpClient.API_APP_ANDROID_PUSH;
        message.mParams = mList;
        AsynHttpClient.getInstance(ForgetActivity.this).execUserHttp(message);

    }

    private void getRongToken(){

        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID_OLD,LocalLogin.getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_USER_ID,mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID,"")));

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_RONG_TOKEN));
        msg.mApi = AsynHttpClient.API_RONG_CHAT_TOKEN;
        msg.mParams = nvps;
        msg.type = 1;
        AsynHttpClient.getInstance(this).execRongHttp(msg);


    }

    private void connectRongYun(){
        /**
         * IMKit SDK调用第二步,建立与服务器的连接
         */
        RongIM.connect(mRongToken, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
             */
            @Override
            public void onTokenIncorrect() {
//                getRongToken();
                Log.d("融云connect", "--onTokenIncorrect");
            }

            /**
             * 连接融云成功
             * @param userid 当前 token
             */
            @Override
            public void onSuccess(String userid) {

                Log.d("融云connect", "--onSuccess" + userid);
                httpReqDlgDismiss();
                mPreferenceUtil.save("isLogin","yes");
                mPreferenceUtil.save("Other_login",0);  // 其他设备登录标识
                Intent intent = new Intent();
                intent.setClass(ForgetActivity.this,MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                ForgetActivity.this.finish();
                LoginActivity.instance.finish();
            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

                Log.d("融云connect", "--onError" + errorCode);
            }
        });
    }

}
